package com.sky.Task;
/**
 * 自定义定时任务类
 */

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.websocket.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Slf4j
public class Task {
    @Autowired
    WebSocket webSocket;
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟触发一次
    public void processTimeoutOrder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list =  orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,localDateTime);
        if(list != null && list.size() > 0){
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时未支付，系统自动取消");
                orderMapper.update(orders);
            }
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("定时处理待发货订单：{}", LocalDateTime.now());
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> list =  orderMapper.getByStatusAndOrderTimeLT(Orders.PAID,localDateTime);
        if(list != null && list.size() > 0)
            for (Orders orders : list){
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void sendMessage(){

        webSocket.sendToAllClient("定时任务发送的消息"+ DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
    }

}
